#include "client.h"

void show_client_files(char* path){
    char local_ls[500]={0};
    char temp_each_size[20];
    char temp_path[200]={0};
    DIR *dirp = opendir(path);
    ERROR_CHECK(dirp, NULL, "opendir");
    // dirent结构体指针，用于存放目录项信息
    strcat(local_ls,"本地目录下:");
    strcat(local_ls," n:普通文件,d:目录\n");
    struct dirent *pdirent;
    // 读取目录中的每个目录项
    int send_count=0;
    while ((pdirent = readdir(dirp)) != NULL) {
        send_count++;
        // 获取文件相关的信息
        if(strcmp(pdirent->d_name,".")==0){
            continue;
        }
        if(strcmp(pdirent->d_name,"..")==0){
            continue;
        }
        if(strcmp(pdirent->d_name,"Makefile")==0){
            continue;
        }
        if(strcmp(pdirent->d_name,"client")==0){
            continue;
        }
        const char *ext=strrchr(pdirent->d_name,'.');
        if (ext != NULL) {
            if (strcmp(ext, ".h") == 0 ||
                strcmp(ext, ".c") == 0 ||
                strcmp(ext, ".o") == 0) {
                continue;
            } else {
            }
        } else {
        }
        struct stat stat_buf;
        bzero(temp_path,sizeof(temp_path));
        strcat(temp_path,path);
        strcat(temp_path,"/");
        strcat(temp_path,pdirent->d_name);
        int ret = stat(temp_path, &stat_buf);
        ERROR_CHECK(ret, -1, "stat");
        bzero(temp_each_size,sizeof(temp_each_size));
        double  mb=1.0*stat_buf.st_size/1024/1024;
        int kb=stat_buf.st_size/1024;
        if(mb>=1.0){
            snprintf(temp_each_size,sizeof(temp_each_size),"%5.2lfMB",mb);
        }else{
            snprintf(temp_each_size,sizeof(temp_each_size),"%dKB",kb);
        }
        int is_dir_flag=0;
        if(S_ISREG(stat_buf.st_mode)){
            strcat(local_ls,"n-");
        }else if(S_ISDIR(stat_buf.st_mode)){
            is_dir_flag=1;
            strcat(local_ls,"d-");
        }else if(S_ISLNK(stat_buf.st_mode)){
            strcat(local_ls,"l-");
        }
        strcat(local_ls,pdirent->d_name);
        if(!is_dir_flag){
            strcat(local_ls," ");
            strcat(local_ls,temp_each_size);
        }else{
            strcat(local_ls,"/");
        }
        strcat(local_ls,"  ");
        /* pdirent->d_name);        // 字符串打印 */
    }
    // 关闭目录流
    if(send_count==2){
        strcat(local_ls,"the cur directory nothing\n");
    }
    printf("%s\n",local_ls);
    closedir(dirp);

}

